import echarts from "echarts";
import zrender from "zrender";
import { addCircleToChart, animateRotate } from "./base";
import { toRad } from "../utils";

const elements = {};

function draw(chart, percentage){
  let gradient = new echarts.graphic.RadialGradient(0.5, 0.5, 0.5, [
    { offset: 0, color: "rgba(0, 0, 0, 0)" },
    { offset: 1, color: "rgba(0, 138, 175, 0.5)" }
  ]);

  var gradient2 = new echarts.graphic.LinearGradient(0, 0.5, 1, 0.5, [
    {
      offset: 0,
      color: "transparent"
    },
    {
      offset: 1,
      color: "#009adb"
    }
  ]);
  var gradient2Rev = new echarts.graphic.LinearGradient(0, 0.5, 1, 0.5, [
    {
      offset: 0,
      color: "#009adb"
    },
    {
      offset: 1,
      color: "transparent"
    }
  ]);

  let zr = chart.getZr();
  let cx = zr.getWidth() / 2;
  let cy = zr.getHeight() / 2;

  let arcs = [];
  let arcOpts = [
    {
      startAngle: toRad(60),
      endAngle: toRad(120),
      reverse: true
    },
    {
      startAngle: toRad(180),
      endAngle: toRad(240),
      reverse: false
    },
    {
      startAngle: toRad(300),
      endAngle: toRad(360),
      reverse: false
    }
  ];

  arcOpts.forEach(arcOpt => {
    let arc = new zrender.Arc({
      origin: [cx, cy],
      shape: {
        cx: cx,
        cy: cy,
        r: 60,
        startAngle: arcOpt.startAngle,
        endAngle: arcOpt.endAngle
      },
      style: {
        fill: null,
        stroke: arcOpt.reverse ? gradient2Rev : gradient2,
        lineWidth: 2
      }
    });
    arcs.push(arc);
  });

  arcs.forEach(arc => {
    animateRotate(arc)
    zr.add(arc);
  });

  let circle = new zrender.Circle({
    origin: [cx, cy],
    shape: {
      cx: cx,
      cy: cy,
      r: 50
    },
    style: {
      fill: gradient,
      fillOpacity: 0.5,
      stroke: "#009adb",
      lineWidth: 1,
      text: percentage + '%',
      fontSize: "20",
      textFill: "#009adb"
    }
  });

 
  addCircleToChart(chart, 60, 2, 120);
  addCircleToChart(chart, 60, 2, 130);
  addCircleToChart(chart, 60, 2, 240);
  addCircleToChart(chart, 60, 2, 250);
  addCircleToChart(chart, 60, 2, 360);
  addCircleToChart(chart, 60, 2, 10);

  zr.add(circle);
  elements.circle = circle;
}

function update(percentage) {
  elements.circle.attr({
    style: {
      text: percentage + '%',
    }
  });
}


export default {
  draw,
  update
}
